import struct
from socket import *

client = socket(AF_INET, SOCK_STREAM)

client.connect(('127.0.0.1', 8080))
while True:

    cmd = input('输入命令:').strip()
    if len(cmd) == 0:
        continue
    client.send(cmd.encode('utf-8'))
    # 粘包问题
    # tcp是流式协议，数据像水流一样，没有边界
    # 接受数据超出接受值会收不干净

    # 解决方案
    # 1 拿到接受结果总大小 total_size
    # 2 recv_size=0,循环接受，每次接受 recv_size+=接受长度
    # 3 直到recv_size=total_size 结束循环

    # 接收header，解包获取total_size
    header = client.recv(4)
    total_size = struct.unpack('i', header)[0]  # 解包获取元组第一个
    print(total_size)
    recv_size = 0
    print('执行结果:')
    while recv_size < total_size:
        recv_data = client.recv(64)
        recv_size += len(recv_data)
        print(recv_data.decode('GBK'), end='')

    print()
client.close()
